package com.module.msg.model

import com.module.app.base.BaseViewModel
import com.module.app.utils.UserUtils
import com.module.base.ext.request
import com.module.base.utils.AppUtils
import com.module.base.utils.ToastUtils
import com.module.frame.ext.postEvent
import com.module.msg.bean.MsgBean
import com.module.third.learcloud.lcSave
import com.module.third.qiniu.QiniuRerun
import com.module.third.qiniu.QiniuUtils
import kotlinx.coroutines.flow.MutableSharedFlow

class AddMsgViewModel : BaseViewModel() {

    /**
     *  发布成功
     */
    val publishFlow: MutableSharedFlow<Boolean> by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
        MutableSharedFlow()
    }

    fun publish(title: String, content: String, path: String?, isVideo: Boolean) {
        if (path.isNullOrEmpty()) {
            delPublish(title, content, path, isVideo)
            return
        }
        postEvent(loadDialogShareFlow, true)
        QiniuUtils.upload(path, 0,
            "msg_" + com.module.app.utils.UserUtils.getUserId().toString() + "_" + System.currentTimeMillis(),
            object : QiniuUtils.Listener() {
                override fun onSuc(qiniuRerun: QiniuRerun?) {
                    super.onSuc(qiniuRerun)
                    postEvent(loadDialogShareFlow, false)
                    if (qiniuRerun != null) {
                        delPublish(title, content, qiniuRerun.url, isVideo)
                    } else {
                        onFail()
                    }
                }

                override fun onFail() {
                    super.onFail()
                    postEvent(loadDialogShareFlow, false)
                    ToastUtils.showShort("文件上传失败")
                }
            })
    }

    private fun delPublish(title: String, content: String, url: String?, isVideo: Boolean) {
        request({
            val bean = MsgBean()
            check(!title.isNullOrEmpty()) { "标题不能为空" }
            check(!content.isNullOrEmpty()) { "内容不能为空" }
            var userId = com.module.app.utils.UserUtils.getUserId()
            if (userId.isNullOrEmpty()) {
                userId = AppUtils.getAndroidId()
            }
            bean.let {
                it.title = title
                it.content = content
                it.isHot = false
                it.url = url
                it.userId = userId
                it.userName = com.module.app.utils.UserUtils.getName()
                it.isVideo = isVideo
            }
            lcSave(bean, MsgBean::class.java)
        }, {
            ToastUtils.showLong("提交成功")
            postEvent(publishFlow,true)

        }, {
            ToastUtils.showShort(it.message)
        }, true)
    }


}